package com.jialiang.yojcodesandbox.service.impl.java;

import com.jialiang.yojcodesandbox.model.CodeSandboxCmd;
import com.jialiang.yojcodesandbox.model.ExecuteCodeRequest;
import com.jialiang.yojcodesandbox.model.ExecuteCodeResponse;
import com.jialiang.yojcodesandbox.service.CodeSandboxTemplate;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * Java 原生代码沙箱实现
 */
@Component
public class JavaNativeCodeSandbox extends CodeSandboxTemplate {

    // 前缀区分编程语言
    private static final String PREFIX = File.separator + "java";

    // 代码存放的根目录
    private static final String GLOBAL_CODE_DIR_PATH = File.separator + "tmpCode";

    // 用户代码文件
    private static final String GLOBAL_JAVA_CLASS_NAME = File.separator + "Main.java";

    // 初始化
    public JavaNativeCodeSandbox() {
        super.prefix = PREFIX;
        super.globalCodeDirPath = GLOBAL_CODE_DIR_PATH;
        super.globalCodeFileName = GLOBAL_JAVA_CLASS_NAME;
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        return super.executeCode(executeCodeRequest);
    }

    @Override
    public CodeSandboxCmd getCmd(String userCodeParentPath, String userCodePath) {
        return CodeSandboxCmd
                .builder()
                .compileCmd(String.format("javac -encoding utf-8 %s", userCodePath))
                .runCmd(String.format("java -Xmx64m -Dfile.encoding=UTF-8 -cp %s Main", userCodeParentPath))
                .build();
    }
}
